package com.example.t470p.facechecktickets.DynamicFaceMatch;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.smartshino.face.Stfaceattr;
import com.syn.phoneface.model.result.Result;
import com.syn.phoneface.ui.camera.CameraFaceConfig;
import com.syn.phoneface.ui.camera.live.CameraFaceCallback;
import com.syn.phoneface.ui.view.CameraSurfaceView;
//import com.synjones.handsetDevDemo.R;
import com.example.t470p.facechecktickets.R;
import com.example.t470p.facechecktickets.DynamicFaceMatch.utils.ToastUtils;
import com.example.t470p.facechecktickets.DynamicFaceMatch.view.FrameFaceView;

import de.hdodenhof.circleimageview.CircleImageView;
/**
 * 人脸动态检测
 */
public class FaceTestActivity extends Activity implements CameraFaceCallback {

    public static final int THRESHOLD = 75;
    CameraSurfaceView mSurfaceView;
    FrameFaceView mFrameFaceView;
    CircleImageView mFaceIv;
    CircleImageView mTempIv;
    TextView mHintTv;
    int mCacheFaceNum = 10;
    long mTimeout = 2;
    int mCameraId = CameraFaceConfig.CAMERA_BACK;
    int mCameraIds[]=new int[]{CameraFaceConfig.CAMERA_BACK,CameraFaceConfig.CAMERA_FRONT};
    int cameraIndex =1;
    Bitmap mTemplateBitmap;
    Button mStartBtn;
    private SoundPool mSoundPool;
    private int mSoundId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_test);

        mSurfaceView = (CameraSurfaceView) findViewById(R.id.cameraSurfaceView);
        mSurfaceView.setIsPortrait(isScreenOriatationPortrait(this));
        mFrameFaceView = (FrameFaceView) findViewById(R.id.finderV);
        mHintTv = (TextView) findViewById(R.id.hintTv);
        mFaceIv = (CircleImageView) findViewById(R.id.faceIv);
        mTempIv = (CircleImageView) findViewById(R.id.tempIv);
        mStartBtn = (Button) findViewById(R.id.startBtn);
        mStartBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startBtnClick();
            }
        });
        Button btnChange=(Button)findViewById(R.id.btnChangeCamera);
        btnChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSurfaceView.onPause();
                mCameraId=mCameraIds[cameraIndex++%2];
                initFaceConfig();
                mSurfaceView.onResume();
            }
        });

        Intent intent = getIntent();
        byte[] imgBytes = intent.getByteArrayExtra("img_byte");
        mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 5);
        mSoundId = mSoundPool.load(this, R.raw.hint, 1);
        if (imgBytes != null) {
            mTemplateBitmap = BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length);
            mTempIv.setImageBitmap(mTemplateBitmap);
        }
        initFaceConfig();
    }

    private void startBtnClick() {
        if(mTemplateBitmap==null) {
            ToastUtils.show(this,"请先读取身份证再核验");
            return;
        }
        mStartBtn.setEnabled(false);
        mFaceIv.setVisibility(View.GONE);
        mHintTv.setText("正在检测...");
        mFaceIv.setBorderColor(getResources().getColor(android.R.color.white));
        mTempIv.setBorderColor(getResources().getColor(android.R.color.white));
        mSurfaceView.startMatch(mTemplateBitmap, mTimeout * 1000);
    }


    private void initFaceConfig() {
        CameraFaceConfig config = new CameraFaceConfig.Builder()
                // 设置前置摄像头
                .setCameraId(mCameraId)
                .build();
        mSurfaceView.setCacheSize(mCacheFaceNum);// 设置缓存数量
        mSurfaceView.setSecurityScore(THRESHOLD);// 设置阈值
        mSurfaceView.setFaceConfig(config);
        mSurfaceView.setFaceCallback(this);
        mFrameFaceView.setCameraId(config.getCameraId());
        mSurfaceView.attachFrameView(mFrameFaceView);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mSurfaceView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mSurfaceView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDecodeSuc(Result obj) {
        Stfaceattr faceAttr = obj.getStfaceattr();
        int[] locFace = faceAttr.getLocFace();
        // 画人脸框
        mFrameFaceView.setLocFace(locFace);
    }

    @Override
    public void onDecodeError(Result obj) {
        mFrameFaceView.setLocFace(null);
    }


    @Override
    public void onTimeout() {
        mHintTv.setText("未检测到人脸");
        mStartBtn.setEnabled(true);
        mFaceIv.setBorderColor(getResources().getColor(R.color.colorVerifyError));
        mTempIv.setBorderColor(getResources().getColor(R.color.colorVerifyError));
    }

    @Override
    public void onVerifySuccess(int score,Bitmap bitmap) {
        mHintTv.setText("识别成功");
        mFaceIv.setVisibility(View.VISIBLE);
        mFaceIv.setImageBitmap(bitmap);
        playSound();
        mStartBtn.setEnabled(true);
        mFaceIv.setBorderColor(getResources().getColor(R.color.colorVerifySuccess));
        mTempIv.setBorderColor(getResources().getColor(R.color.colorVerifySuccess));
    }

    @Override
    public void onVerifyFail(Bitmap bitmap) {
        mHintTv.setText("认证失败");
        mFaceIv.setVisibility(View.VISIBLE);
        mFaceIv.setImageBitmap(bitmap);
        playSound();
        mStartBtn.setEnabled(true);
        mFaceIv.setBorderColor(getResources().getColor(R.color.colorVerifyError));
        mTempIv.setBorderColor(getResources().getColor(R.color.colorVerifyError));
    }



    public void playSound() {
        mSoundPool.play(mSoundId, 1, 1, 0, 0, 1);
    }


    public static boolean isScreenOriatationPortrait(Context context) {
        return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }
}
